
auto.dcor = function(A, B, lag = 0){
       A = as.matrix(A)
       B = as.matrix(B)
       N1 = dim(A)[1]
       N2 = dim(B)[1]
       if(N1 != N2) stop("Different Row Lengths")
       lag = floor(as.numeric(lag))
  if(lag < 0) stop("lag must be non-negative integer")
  M = seq(-lag,lag,1)
  adcor = numeric(length(M))
  p.vals = numeric(length(M))
  iter = 1
  for(i in M){
       if(i == 0){
               A.temp = A
               B.temp = B
               }
       if(i < 0){
               A.temp = A[-c(1:(-i)) , ] #remove first i observations
               B.temp = B[-c((N2-(-i)+1):N2) , ] #remove last i observations
               }
       if(i > 0){
               A.temp = A[-c((N1-i+1):N1) , ] #remove last i observations
               B.temp = B[-c(1:i) , ] #remove first i observations
               }
       adcor[iter] = dcor(A.temp, B.temp)
       p.vals[iter] = indep.test(A.temp, B.temp, method = c("dcov"), index = 1, R = 199)$p.value

       iter = iter + 1
       }
  structure(list(lag = M, adcor = adcor, p.vals = p.vals))
 # adcor
}